/**
 * 
 */
package com.tjtt.tdm.filemodel.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.struts2.ServletActionContext;

import com.tjtt.common.utils.ExcelExportUtil;
import com.tjtt.common.utils.StringUtil;
import com.tjtt.tdm.base.BaseAction;
import com.tjtt.tdm.base.PageResult;
import com.tjtt.tdm.base.PubMethod;
import com.tjtt.tdm.exception.DaoException;
import com.tjtt.tdm.exception.ServiceException;
import com.tjtt.tdm.filemodel.bean.DicItem;
import com.tjtt.tdm.filemodel.bean.Filemode;
import com.tjtt.tdm.filemodel.bean.PrintReportMode;
import com.tjtt.tdm.filemodel.bean.RquipmentManage;
import com.tjtt.tdm.filemodel.bean.TdmCentificatemodeItem;
import com.tjtt.tdm.filemodel.bean.TdmFilemodeItem;
import com.tjtt.tdm.filemodel.bean.TdmPrintreportmodeItem;
import com.tjtt.tdm.filemodel.service.IFilemodeService;
import com.tjtt.tdm.form.bean.AutoFormsField;
import com.tjtt.tdm.form.bean.AutoFormsNew;
import com.tjtt.tdm.form.service.IAutoFormService;
import com.tjtt.tdm.form.service.IAutoService;

public class FilemodeAction extends BaseAction{
    /**
	 * 
	 */
	private String id;
	private String modename;
	private String filepath;
	private String extendname;
    private IFilemodeService filemodeService;
    private IAutoService autoService;
    private List uploadfile;
	private List uploadfileContentType;
	private List uploadfileFileName;
	
	private IAutoFormService autoFormService;
	
	public String getModename() {
		return modename;
	}

	public void setModename(String modename) {
		this.modename = modename;
	}

	public String getFilepath() {
		return filepath;
	}

	public void setFilepath(String filepath) {
		this.filepath = filepath;
	}

	public IFilemodeService getFilemodeService() {
		return filemodeService;
	}

	public void setFilemodeService(IFilemodeService filemodeService) {
		this.filemodeService = filemodeService;
	}

	public void queryFilemodeList()
    {
    	try {
    		Map<String, String> filterMap = getPagerMap();
		    //取出页面中的查询条件
			String modelTypeName ;
			String id=getRequest().getParameter("id");
			String flag=getRequest().getParameter("flag");
			String type=getRequest().getParameter("type");
			String modelCatalogue=getRequest().getParameter("modelCatalogue");
			filterMap.put("modelCatalogue", modelCatalogue);
			String[] viewArray = { "ID", "FILENAME","FILEPATH", "ORG_NAME", "GONGYI_NAME", "CREATETIME"};
			String returnStr = "";
			if("1".equals(flag)){
				// 查询所有的数据
				PageResult result = filemodeService.queryFilemodeList(filterMap);
				returnStr=getColumnJson(result, viewArray);
			}else if("2".equals(flag)){
				PageResult result = filemodeService.getModelByPid(Integer.parseInt(type), filterMap);
				returnStr = getColumnJson(result, viewArray);
				
			}
			PrintWriter out = PubMethod.GetPrintWriter(); 
			System.out.println("--!"+returnStr+"--!");
			out.print(returnStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
	
	
	public  void daoRuExcel()
	{
		PrintWriter out = PubMethod.GetPrintWriter(); 
		String flag = getRequest().getParameter("flag");
		String id = getRequest().getParameter("id");
		String path ="";
		try
		{
			List files = getUploadfile();
			if (files!=null)
			{
				for (int i = 0 ; i < files.size() ; i++) 
				{ 
					String fileName = (String) getUploadfileFileName().get(i);
					String fileType = fileName.substring((fileName.lastIndexOf("."))+1, fileName.length());
					File ff = new File(files.get(i).toString());
					if(ff.length()>0)
					{
				        String url = getRequest().getSession().getAttribute("SYS_FILEPATH").toString();
				        url = url+"/importfile";
						File file = new File(url);
						if ( ! (file.exists())  &&   ! (file.isDirectory()))  {
			                 boolean  creadok  =  file.mkdirs();
			                 if (creadok)  {
			                    System.out.println( " ok:创建文件夹成功！ " );
			                } else  {
			                    System.out.println( " err:创建文件夹失败！ " );                    
			                } 
			            } 
						SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmssSSS");
						path = url +"/"+sdf1.format(System.currentTimeMillis())+"."+ fileType;
						FileOutputStream fos = new FileOutputStream(path); 
						FileInputStream fis = new FileInputStream(files.get(i).toString()); 
						byte[] buffer = new byte[1024]; 
						int len = 0; 
						while ((len = fis.read(buffer)) > 0) 
						{ 
							fos.write(buffer, 0, len);
						} 
						fos.close();
						fis.close();
					}
				}
			}
			
			File file = new File(path);
			List<String[]> result = new ArrayList<String[]>();
				result = read2007Excel(file);
				if("0".equals(flag)){//flag=0 为样品模版导入
					for(int i=1;i<result.size();i++){
						String[] strs =result.get(i);//TDM_TECHNICAL
							String sampleName = "";     //样品名称
							Long sampleCount = null;     //样品数量
							String picihao = "";        //批次号/规格型号
							String chexingId = "";    //应用车型
							String bianma ="" ;         //车型编码
							String chanshang = "";      //生产商
							String riqi ="";            //约定送样日期
							String samplechuli = "";    //样品处理
							if(  null !=  strs[0] && !strs[0].equals("")){
								sampleName = strs[0].toString();
							}
							if(  null !=  strs[1] && !strs[1].equals("")){
								sampleCount =Long.parseLong(strs[1]);
							}
							if(  null !=  strs[2] && !strs[2].equals("")){
								picihao = strs[2].toString();
							}
							if(  null !=  strs[3] && !strs[3].equals("")){
								//根据应用车型查询车型ID
								String  chexingName = strs[3].toString();
								String sql = "select t.id from gwm_applicationmode t where t.t_chexingname='"+chexingName+"'";
								List list = autoFormService.getDatabySql(sql);
								if(null!=list&&list.size()>0&&null!=list.get(0)){
									chexingId = list.get(0).toString();
								}
							}
							if(  null !=  strs[4] && !strs[4].equals("")){
								bianma = strs[4].toString();
							}
							if(  null !=  strs[5] && !strs[5].equals("")){
								chanshang = strs[5].toString();
							}
							if(  null !=  strs[6] && !strs[6].equals("")){
								riqi = strs[6].toString();
							}
							if(  null !=  strs[7] && !strs[7].equals("")){
								samplechuli = strs[7].toString();
							}
							String insertSql = "insert into gwm_sample(id, t_samplename, t_samplecount, t_pici, t_yingyongchexing, t_chexingbianma, t_manufacturer, t_songyangdate, t_samplechuli, t_annex, t_taskid, t_sampleno) values " +
									            "(SEQ_GWM_SAMPLE.Nextval,'"+sampleName+"',"+sampleCount+",'"+picihao+"','"+chexingId+"','"+bianma+"','"+chanshang+"','"+riqi+"','"+samplechuli+"','', "+id+",'')";
					        autoFormService.executeSql(insertSql);
					}
				}
				out.print("{\"result\":\"success\"}");
				out.flush();
						
		}
		catch (Exception e)
		{
			out.print("{\"result\":\"error\"}");
			e.printStackTrace();
		}
	}
	public void lotSizeReadonly() throws DaoException{
		PrintWriter out = PubMethod.GetPrintWriter(); 
		String id=getRequest().getParameter("id");
		if(id.indexOf(",")==-1){
			String buttonSql = "update TDM_FILEMODE_ITEM t set t.WHETHOR_READONLY = 1 where t.id ="+id;
    		autoService.executeSql(buttonSql);
		}else{
			String[] str = id.split(",");
			for(int i=0;i<str.length;i++){
				String buttonSql = "update TDM_FILEMODE_ITEM t set t.WHETHOR_READONLY = 1 where t.id ="+str[i];
	    		autoService.executeSql(buttonSql);
			}
		}
		out.print("{\"ajaxResult\":\"success\"}");
		out.flush();
	}
	public void exportJiShuTiaoJian() throws UnsupportedEncodingException{
		List<String> list = new ArrayList<String>();
		List<String> fieldlist = new ArrayList<String>();
		List<String> fieldlist1 =new ArrayList<String>();
		String extitleName="";
		//String titleNames= StringUtil.encodingUrl(getRequest().getParameter("titleNames"));
		//String fieldsNames= getRequest().getParameter("fieldsNames");
		String titleNames= "检测依据,材料牌号,首件,规格,锻件类别,状态,检测室,项目组,检验项目,检测方法,腐蚀剂,项目单价,标准要求,判定上限符号,判定上限,判定下限,判定下限符号,上限偏差,下限偏差,保留位数,判定公式,判定等级,项目数据单位,加工方式,加工数量,加工价格,热处理项目,热处理价格,备注,项目顺序,判定公式上限,判定公式下限,";
		String fieldsNames="T_JSTJ,T_CLPH,T_SFSJ,T_GUIH,T_JLLB,T_ZT,T_JCS,T_XMZ,T_JYXM,T_JCFF,T_FSJ,T_XMDJ,T_BZYQ,T_PDSXFH,T_PDSX,T_PDXX,T_PDXXFH,T_SXPC,T_XXPC,T_BLWS,T_PDGS,T_PDDJ,T_XMSJDW,T_JGFS,T_JGSL,T_JGJG,T_RCLXM,T_RCLJG,T_BZ,T_XMSX,T_PGSSX,T_PDGSXX,";
		String T_JYXM = StringUtil.encodingUrl(getRequest().getParameter("T_JYXM"));
		String T_JSTJ = StringUtil.encodingUrl(getRequest().getParameter("T_JSTJ"));
		String T_CLPH = StringUtil.encodingUrl(getRequest().getParameter("T_CLPH"));
		String T_JCS = StringUtil.encodingUrl(getRequest().getParameter("T_JCS"));
		String ids = StringUtil.encodingUrl(getRequest().getParameter("ids"));
		
		if(!"".equals(titleNames)&&titleNames!=null){
			extitleName = new String(titleNames);
            //extitleName = new String(titleNames.getBytes("ISO8859-1"), "UTF-8");
	
			String[] titleName=extitleName.split(",");
			for (int i=0;i<titleName.length;i++) {
				list.add(titleName[i]);
			}
			if(null != fieldsNames){
				String[] fieldsName=fieldsNames.split(",");
				for (int j=0;j<fieldsName.length;j++) {
					fieldlist.add(fieldsName[j].toUpperCase());
				}
			}
			
			String[] s = { "ID","T_JSTJ","T_CLPH","T_SFSJ","T_GUIH","T_JLLB","T_ZT","T_JCS","T_XMZ","T_JYXM","T_JCFF","T_FSJ","T_XMDJ","T_BZYQ","T_PDSXFH","T_PDSX","T_PDXX","T_PDXXFH","T_SXPC","T_XXPC","T_BLWS","T_PDGS","T_PDDJ","T_XMSJDW","T_JGFS","T_JGSL","T_JGJG","T_RCLXM","T_RCLJG","T_BZ","T_XMSX","T_PGSSX","T_PDGSXX"};
			
			
			for(int i=0;i<s.length;i++){
				fieldlist1.add(s[i].toUpperCase());
			}
			
		}
		Map filterMap = getPagerMap();
		filterMap.put("T_JYXM", T_JYXM);
		filterMap.put("T_JSTJ", T_JSTJ);
		filterMap.put("T_CLPH", T_CLPH);
		filterMap.put("T_JCS", T_JCS);
		filterMap.put("ids", ids);
		ExcelExportUtil excelutil = new ExcelExportUtil();
		String userNm = ServletActionContext.getRequest().getSession().getAttribute("username").toString();
//		File file = new File("d:"+File.separator);
		String fileName1 ="检测依据导出信息.xlsx";//
		String fileName ="exportjstj.xlsx";
		try {
			filterMap.put("rows",999);
			List setListForExcel=filemodeService.queryJiShuTiaoJianList(filterMap).getData();
			//excelutil.exportlhExcel(fileName,list,fieldlist,fieldlist1,filterMap,setListForExcel,userNm,new Timestamp(System.currentTimeMillis()));
			System.out.println("====="+fieldlist);
			ExcelExportUtil exExcelUtil = new ExcelExportUtil();
			List<Map<String, Object>> dataList = getDataList(fieldlist1,filterMap,setListForExcel);
			List<String> headList = list;
			List<String> fieldList = fieldlist;	
			XSSFWorkbook wb = new XSSFWorkbook();
			String filePath =  getRequest().getSession().getAttribute("SYS_FILEPATH").toString()+"/export/"+PubMethod.GetTimerName()+"/";
			File targetFile = new File(filePath);
			if ( ! (targetFile.exists())  &&   ! (targetFile.isDirectory()))  {
		        boolean  creadok  =  targetFile.mkdirs();
		        if (creadok)  {
		           System.out.println( " ok:创建文件夹成功！ " );
		       } else  {
		           System.out.println( " err:创建文件夹失败！ " ); 
		
		           
		       } 
		   } 
			filePath = filePath + fileName;
			File targetFile1 = new File(filePath);
			if (targetFile1.exists()) {
				targetFile1.delete();
			} else {
				targetFile1.createNewFile();
			}
			FileOutputStream fileOut = new FileOutputStream(filePath);
			// 创建新的Excel 工作簿
			// 在Excel工作簿中建一工作表，其名为缺省值
			// 如要新建一名为"效益指标"的工作表，其语句为：
			// HSSFSheet sheet = workbook.createSheet("效益指标");
			XSSFSheet sheet = wb.createSheet();
			// 在索引0的位置创建行（最顶端的行）
			XSSFRow row = sheet.createRow(0);
			for (int i = 0; i < headList.size(); i++) {
				XSSFCell cell = row.createCell(i);
				cell.setCellType(XSSFCell.CELL_TYPE_STRING);
				cell.setCellValue(headList.get(i));
			}
			String str1;
			for (int n = 0; n < dataList.size(); n++) {
				XSSFRow row_value = sheet.createRow(n + 1);
				Map<String, Object> dataMap = dataList.get(n);
				for (int i = 0; i < fieldList.size(); i++) {
					XSSFCell cell = row_value.createCell(i);
					cell.setCellType(XSSFCell.CELL_TYPE_STRING);
					str1=objToString(dataMap.get(fieldList.get(i)));
					if(DataTypeJudge(fieldList.get(i))){
						cell.setCellValue(DataTypeToCN(fieldList.get(i),dataMap.get(fieldList.get(i))));
					}else{
						cell.setCellValue(objToString(dataMap.get(fieldList.get(i))));
					}
				}
			}
			wb.write(fileOut);
			fileOut.close();
				if(targetFile1.exists())
				{
					getResponse().setHeader("Server","www.tjtt.com");
					getResponse().setHeader("Content-Type", "application/octet-stream");
					getResponse().setHeader("Content-Length", String.valueOf(targetFile1.length()));
					getResponse().setHeader("Content-Disposition", "attachment; filename=\"" + java.net.URLEncoder.encode(fileName1,"UTF-8").replace( "+",   "%20")  + "\"");	
					try {
						OutputStream downloadStream=getResponse().getOutputStream();
						FileInputStream fin = new FileInputStream(targetFile1);
						byte[] b=new byte[1024];	
						int length=fin.read(b);
						while(length>0)
						{
							downloadStream.write(b,0,length);
							length=fin.read(b);
						}
						downloadStream.flush();
//						fin.close();	
						//addMessage("下载成功！");
					} catch (IOException e) {
						e.printStackTrace();
					}			
				}	
			
				// fileOut.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private List<Map<String, Object>> getDataList(List<String> fieldlist,Map filterMap,List setListForExcel) {
		/**
		 * 数据集合
		 */
		List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
		List<?> list = new ArrayList(); 
		list =setListForExcel;
		String[] st = new String[fieldlist.size()];
		Object[] obj = new Object[list.size()];
		for(int j=0;j<list.size();j++){
			Map<String, Object> map = new HashMap<String, Object>();
			obj = (Object[])list.get(j);
//			System.out.print(obj);
			for(int i=0;i<fieldlist.size();i++){
				map.put((String)fieldlist.get(i),obj[i]);
			}
			dataList.add(j,map);
			
		}
		return dataList;
	}
	/***
	 * 判断业务状态进行输出控制
	 * @return
	 */
	private static String DataTypeToCN(Object obj1,Object obj2) {
		/*if(obj1.toString().equals("STATE")){
			if(obj2.toString().equals("0")){
				return "aaaaaa";
			}else if(obj2.toString().equals("1")){
				return "bbbb";
			}else{
				return "acbdfweerfqwe";	
			}
		}else if(obj1.toString().equals("OVERDATE")){
			return obj2.toString().split("-")[1]+"月";
			
		}else{*/
			return obj1.toString();
//		}
		
	}
	/***
	 * 判断此字段数据是否值得进行逻辑值的转换
	 * @param obj
	 * @return
	 */
	private static Boolean DataTypeJudge(Object obj) {
		/*if(obj.toString().equals("STATE")){
			return true;
		}else if(obj.toString().equals("OVERDATE")){
			return true;
		}else{
			
		}*/return false;
	}
	private static String objToString(Object obj) {
		if (obj == null) {
			return "";
		} else {
			if (obj instanceof String) {
				return (String) obj;
			} else if (obj instanceof Date) {
				//return dateToString();
				SimpleDateFormat stf=new SimpleDateFormat("yyyy-MM-dd");
				String str=stf.format(obj);
				return str;
				//return null;// DateUtil.dateToString((Date)
				// obj,DateUtil.DATESTYLE_SHORT_EX);
			} else {
				return obj.toString();
			}
		}
	}
	public static List<String[]> read2003Excel(File file) throws FileNotFoundException, IOException{
		List<String[]> result = new ArrayList<String[]>();
		//创建新的 excel工作簿
		HSSFWorkbook hwb = new HSSFWorkbook(new FileInputStream(file));
		HSSFSheet sheet = hwb.getSheetAt(0);
		//循环每行
		for(int rowIndex=0;rowIndex<=sheet.getLastRowNum();rowIndex++){
			HSSFRow row = sheet.getRow(rowIndex+1);//得到每一行的数据 
			if(row==null){
				continue;
			}
			String[] rowArray = new String[sheet.getRow(0).getLastCellNum()];
			//循环每列
			for (short columnIndex = 0; columnIndex <row.getLastCellNum(); columnIndex++) {
				String value = "";
				HSSFCell cell  = row.getCell(columnIndex);
				if(cell!=null){
					switch (cell.getCellType()) {
					case XSSFCell.CELL_TYPE_STRING:
						value = cell.getStringCellValue();
						break;
					case XSSFCell.CELL_TYPE_NUMERIC:
						if(HSSFDateUtil.isCellDateFormatted(cell)){
							Date date = cell.getDateCellValue();
							if(date!=null){
								value = new SimpleDateFormat("yyyy-MM-dd").format(date);
							}else{
								value = "";
							}
						}else{
							value = new DecimalFormat("0").format(cell.getNumericCellValue());
						}
						break;
					case XSSFCell.CELL_TYPE_FORMULA:
						// 导入时如果为公式生成的数据则无值
						if(!cell.getStringCellValue().equals("")){
							value = cell.getStringCellValue();
						}else{
							value = cell.getNumericCellValue()+"";
						}
						break;
					case XSSFCell.CELL_TYPE_BOOLEAN:
						value = (cell.getBooleanCellValue()==true?"Y":"N");
						break;
					case XSSFCell.CELL_TYPE_BLANK:
						value = "";
						break;
					case XSSFCell.CELL_TYPE_ERROR:
						value = "";
						break;
					default:
						value = cell.toString();
					}
				}
				rowArray[columnIndex]=value;
			}
			result.add(rowArray);
		}
		return result;
	}
	public static List<String[]>  read2007Excel(File file) throws FileNotFoundException, IOException{
		List<String[]> result = new ArrayList<String[]>();
		HSSFWorkbook hssfWorkbook = new HSSFWorkbook(new FileInputStream(file));
		//第一个sheet
		HSSFSheet sheet = hssfWorkbook.getSheetAt(0);
		//sheet.getLastRowNum() sheet最后一行的行号
		for(int rowIndex=0;rowIndex<=sheet.getLastRowNum();rowIndex++){
			//获得行
			 HSSFRow row = sheet.getRow(rowIndex + 1);
			if(row==null){
				continue;
			}
			//sheet.getRow(0).getLastCellNum() 获得一行有多少列
			String[] rowArray = new String[sheet.getRow(0).getLastCellNum()];
			for(short columnIndex=0;columnIndex<row.getLastCellNum();columnIndex++){
				String value = "";
				HSSFCell cell = row.getCell(columnIndex);//得到的每行的每个具体的值 
				if(cell!=null){
					switch (cell.getCellType()) {
					case XSSFCell.CELL_TYPE_STRING:
						value = cell.getStringCellValue();
						break;
					case XSSFCell.CELL_TYPE_NUMERIC:
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");// 格式化日期字符串
						if ("General".equals(cell.getCellStyle().getDataFormatString())) {
							value = new DecimalFormat("0").format(cell.getNumericCellValue());
						} else {
							value = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue()));
						}
						break;
					case XSSFCell.CELL_TYPE_FORMULA:
						// 导入时如果为公式生成的数据则无值
						if (!cell.getStringCellValue().equals("")) {
							value = cell.getStringCellValue();
						} else {
							value = cell.getNumericCellValue() + "";
						}
						break;
					case XSSFCell.CELL_TYPE_BLANK:
						break;
					case XSSFCell.CELL_TYPE_ERROR:
						value = "";
						break;
					case XSSFCell.CELL_TYPE_BOOLEAN:
						value = (cell.getBooleanCellValue() == true ? "Y" : "N");
						break;
					default:
						value = "";
						break;
					}
				}
				rowArray[columnIndex]=value;
			}
			result.add(rowArray);
		}
		return result;
	}
	  
	   
	public void queryModeItemList()
    {
    	try {
    		Map<String, String> filterMap = getPagerMap();
		    //取出页面中的查询条件
			String modelTypeName ;
			String id=getRequest().getParameter("id");
			String fileModeId=getRequest().getParameter("fileModeId");
			filterMap.put("fileModeId", fileModeId);
			String[] viewArray = { "ID", "ITEM_NAME", "PROJECT_NAME","METHOD_NAME", "STANDARD_NAME","FORM_CNAME", "FORM_ENAME","FIELD_CNAME", "FIELD_ENAME", "BQ_TYPE:[{'0':'excel导入','1':'表单','2':'手动输入','3':'动态行列标签','4':'特殊标签'}]"};
			String returnStr = "";
			PageResult result = filemodeService.queryModeItemList(filterMap);
			returnStr=getColumnJson(result, viewArray);
			PrintWriter out = PubMethod.GetPrintWriter(); 
			System.out.println("--!"+returnStr+"--!");
			out.print(returnStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
	
	public void queryItemList()
    {
    	try {
    		String itemname = this.getRequest().getParameter("itemname");
    		String jianceleibie = this.getRequest().getParameter("jianceleibie");
    		Map<String, String> filterMap = getPagerMap();
    		filterMap.put("itemname", itemname);
    		filterMap.put("jianceleibie", jianceleibie);
		    //取出页面中的查询条件
			String[] viewArray = { "id","t_itemname","T_JIANCECANSHU","t_jiaceleibie","T_JIANCEDANWEI_NAME","T_JIANCEDIDIAN"};
			String returnStr = "";
			PageResult result = filemodeService.queryItemList(filterMap);
			returnStr=getColumnJson(result, viewArray);
			PrintWriter out = PubMethod.GetPrintWriter(); 
			out.print(returnStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
	public void queryCentificateItemList()
    {
    	try {
    		Map<String, String> filterMap = getPagerMap();
		    //取出页面中的查询条件
			String modelTypeName ;
			String id=getRequest().getParameter("id");
			String fileModeId=getRequest().getParameter("fileModeId");
			filterMap.put("fileModeId", fileModeId);
			String[] viewArray = { "ID", "ITEM_NAME","METHOD_NAME", "STANDARD_NAME","FORM_CNAME", "FORM_ENAME","FIELD_CNAME", "FIELD_ENAME", "BQ_TYPE:[{'0':'项目','1':'流程','2':'项目相关'}]"};
			String returnStr = "";
			PageResult result = filemodeService.queryCentificateItemList(filterMap);
			returnStr=getColumnJson(result, viewArray);
			PrintWriter out = PubMethod.GetPrintWriter(); 
			System.out.println("--!"+returnStr+"--!");
			out.print(returnStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
	
	public void queryPrintReportItemList()
    {
    	try {
    		Map<String, String> filterMap = getPagerMap();
		    //取出页面中的查询条件
			String modelTypeName ;
			String id=getRequest().getParameter("id");
			String fileModeId=getRequest().getParameter("fileModeId");
			filterMap.put("fileModeId", fileModeId);
			String[] viewArray = { "ID", "ITEM_NAME","METHOD_NAME", "STANDARD_NAME","FORM_CNAME", "FORM_ENAME","FIELD_CNAME", "FIELD_ENAME", "BQ_TYPE:[{'0':'excel导入','1':'表单','2':'手动输入','3':'动态行列标签','4':'特殊标签'}]"};
			String returnStr = "";
			PageResult result = filemodeService.queryPrintReportItemList(filterMap);
			returnStr=getColumnJson(result, viewArray);
			PrintWriter out = PubMethod.GetPrintWriter(); 
			System.out.println("--!"+returnStr+"--!");
			out.print(returnStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
	public void daoRuFileModeItem() throws DaoException{
		PrintWriter out = PubMethod.GetPrintWriter(); 
		String ids=getRequest().getParameter("id");
		String fileModeId=getRequest().getParameter("fileModeId");
		String type = getRequest().getParameter("type");
		String flag = getRequest().getParameter("flag");
		
//		if("word".equals(type)){
//			if(ids.indexOf(",")==-1){//只有一个id
//				AutoFormsField autoFormsField = filemodeService.findAuToFormsField(Long.parseLong(ids));
//				AutoFormsNew autoFormsNew = filemodeService.findAuToFormsNew(autoFormsField.getFormsId());
//				TdmCentificatemodeItem tdmCentificatemodeItem = new TdmCentificatemodeItem();
//				tdmCentificatemodeItem.setItemName(autoFormsField.getCnName());
//				tdmCentificatemodeItem.setFieldCname(autoFormsField.getCnName());
//				tdmCentificatemodeItem.setFieldEname(autoFormsField.getFieldName());
//				tdmCentificatemodeItem.setFormCname(autoFormsNew.getFormCnName());
//				tdmCentificatemodeItem.setFormEname(autoFormsNew.getFormEnName());
//				tdmCentificatemodeItem.setCentificateModeId(Long.parseLong(fileModeId));
//				tdmCentificatemodeItem.setType(1l);
//				tdmCentificatemodeItem.setBqType(1l);
//				filemodeService.save(tdmCentificatemodeItem);
//			}else{//有多个id
//				String[] str = ids.split(",");
//				
//				for(int i=0;i<str.length;i++){
//					AutoFormsField autoFormsField = filemodeService.findAuToFormsField(Long.parseLong(str[i]));
//					AutoFormsNew autoFormsNew = filemodeService.findAuToFormsNew(autoFormsField.getFormsId());
//					TdmCentificatemodeItem tdmCentificatemodeItem = new TdmCentificatemodeItem();
//					tdmCentificatemodeItem.setItemName(autoFormsField.getCnName());
//					tdmCentificatemodeItem.setFieldCname(autoFormsField.getCnName());
//					tdmCentificatemodeItem.setFieldEname(autoFormsField.getFieldName());
//					tdmCentificatemodeItem.setFormCname(autoFormsNew.getFormCnName());
//					tdmCentificatemodeItem.setFormEname(autoFormsNew.getFormEnName());
//					tdmCentificatemodeItem.setCentificateModeId(Long.parseLong(fileModeId));
//					tdmCentificatemodeItem.setType(1l);
//					tdmCentificatemodeItem.setBqType(1l);
//					filemodeService.save(tdmCentificatemodeItem);
//				}
//			}
//			out.print("{\"ajaxResult\":\"success\"}");
//			out.flush();
//		}else
			
	   if("excel".equals(type)||"word".equals(type)){
			if(ids.indexOf(",")==-1){//只有一个id
				AutoFormsField autoFormsField = filemodeService.findAuToFormsField(Long.parseLong(ids));
				AutoFormsNew autoFormsNew = filemodeService.findAuToFormsNew(autoFormsField.getFormsId());
				TdmFilemodeItem tdmFilemodeItem = new TdmFilemodeItem();
				tdmFilemodeItem.setItemName(autoFormsField.getCnName());
				tdmFilemodeItem.setFieldCname(autoFormsField.getCnName());
				tdmFilemodeItem.setFieldEname(autoFormsField.getFieldName());
				tdmFilemodeItem.setFormCname(autoFormsNew.getFormCnName());
				tdmFilemodeItem.setFormEname(autoFormsNew.getFormEnName());
				tdmFilemodeItem.setFileModeId(Long.parseLong(fileModeId));
				tdmFilemodeItem.setType(1l);
				if(!"".equals(flag)&&"0".equals(flag)){
					tdmFilemodeItem.setBqType(1l);
				}
				else if(!"".equals(flag)&&"1".equals(flag)){
					tdmFilemodeItem.setBqType(3l);
				} 
				else if(!"".equals(flag)&&"2".equals(flag)){
					tdmFilemodeItem.setBqType(4l);
				} 
				filemodeService.save(tdmFilemodeItem);
			}else{//有多个id
				String[] str = ids.split(",");
				
				for(int i=0;i<str.length;i++){
					AutoFormsField autoFormsField = filemodeService.findAuToFormsField(Long.parseLong(str[i]));
					AutoFormsNew autoFormsNew = filemodeService.findAuToFormsNew(autoFormsField.getFormsId());
					TdmFilemodeItem tdmFilemodeItem = new TdmFilemodeItem();
					tdmFilemodeItem.setItemName(autoFormsField.getCnName());
					tdmFilemodeItem.setFieldCname(autoFormsField.getCnName());
					tdmFilemodeItem.setFieldEname(autoFormsField.getFieldName());
					tdmFilemodeItem.setFormCname(autoFormsNew.getFormCnName());
					tdmFilemodeItem.setFormEname(autoFormsNew.getFormEnName());
					tdmFilemodeItem.setFileModeId(Long.parseLong(fileModeId));
					tdmFilemodeItem.setType(1l);
					if(!"".equals(flag)&&"0".equals(flag)){
						tdmFilemodeItem.setBqType(1l);
					}
					else if(!"".equals(flag)&&"1".equals(flag)){
						tdmFilemodeItem.setBqType(3l);
					}
					else if(!"".equals(flag)&&"2".equals(flag)){
						tdmFilemodeItem.setBqType(4l);
					} 
					filemodeService.save(tdmFilemodeItem);
				}
			}
			out.print("{\"ajaxResult\":\"success\"}");
			out.flush();
		}else if("qita".equals(type)){
			if(ids.indexOf(",")==-1){//只有一个id
				AutoFormsField autoFormsField = filemodeService.findAuToFormsField(Long.parseLong(ids));
				AutoFormsNew autoFormsNew = filemodeService.findAuToFormsNew(autoFormsField.getFormsId());
				TdmPrintreportmodeItem tdmPrintreportmodeItem= new TdmPrintreportmodeItem();
				tdmPrintreportmodeItem.setItemName(autoFormsField.getCnName());
				tdmPrintreportmodeItem.setFieldCname(autoFormsField.getCnName());
				tdmPrintreportmodeItem.setFieldEname(autoFormsField.getFieldName());
				tdmPrintreportmodeItem.setFormCname(autoFormsNew.getFormCnName());
				tdmPrintreportmodeItem.setFormEname(autoFormsNew.getFormEnName());
				tdmPrintreportmodeItem.setFileModeId(Long.parseLong(fileModeId));
				tdmPrintreportmodeItem.setType(1l);
				if(!"".equals(flag)&&"0".equals(flag)){
					tdmPrintreportmodeItem.setBqType(1l);
				}
				else if(!"".equals(flag)&&"1".equals(flag)){
					tdmPrintreportmodeItem.setBqType(3l);
				} 
				else if(!"".equals(flag)&&"2".equals(flag)){
					tdmPrintreportmodeItem.setBqType(4l);
				} 
				filemodeService.save(tdmPrintreportmodeItem);
			}else{//有多个id
				String[] str = ids.split(",");
				
				for(int i=0;i<str.length;i++){
					AutoFormsField autoFormsField = filemodeService.findAuToFormsField(Long.parseLong(str[i]));
					AutoFormsNew autoFormsNew = filemodeService.findAuToFormsNew(autoFormsField.getFormsId());
					TdmPrintreportmodeItem tdmPrintreportmodeItem= new TdmPrintreportmodeItem();
					tdmPrintreportmodeItem.setItemName(autoFormsField.getCnName());
					tdmPrintreportmodeItem.setFieldCname(autoFormsField.getCnName());
					tdmPrintreportmodeItem.setFieldEname(autoFormsField.getFieldName());
					tdmPrintreportmodeItem.setFormCname(autoFormsNew.getFormCnName());
					tdmPrintreportmodeItem.setFormEname(autoFormsNew.getFormEnName());
					tdmPrintreportmodeItem.setFileModeId(Long.parseLong(fileModeId));
					tdmPrintreportmodeItem.setType(1l);
					if(!"".equals(flag)&&"0".equals(flag)){
						tdmPrintreportmodeItem.setBqType(1l);
					}
					else if(!"".equals(flag)&&"1".equals(flag)){
						tdmPrintreportmodeItem.setBqType(3l);
					} 
					else if(!"".equals(flag)&&"2".equals(flag)){
						tdmPrintreportmodeItem.setBqType(4l);
					} 
					filemodeService.save(tdmPrintreportmodeItem);
				}
			}
			out.print("{\"ajaxResult\":\"success\"}");
			out.flush();
		}
		
		
		
	}
    public void saveFilemode()
    {
    	try{
    		//获取文件
    		PrintWriter out = PubMethod.GetPrintWriter(); 
    		HttpServletRequest request = this.getRequest();
    		String _modename = request.getParameter("modename");
    		String orgname = request.getParameter("orgname");
    		String orgid = request.getParameter("orgid");
    		String gongyiname = request.getParameter("gongyiname");
    		String gongyiid = request.getParameter("gongyiid");
            String _filepath = request.getParameter("filepath");
            String id=request.getParameter("id");
            String modelCatalogue=request.getParameter("modelCatalogue");
        	Filemode filemode = new Filemode();
        	if(id!=null && !"".equals(id) && !"null".equals(id)){
        		int type=Integer.parseInt(id);
            	filemode.setType(type);
			}else{
            	filemode.setType(1);
            }
        	filemode.setCreateTime(new Timestamp(System.currentTimeMillis()));
    		filemode.setFilename(_modename);
    		filemode.setFilepath(_filepath);
    		filemode.setOrgId(Long.parseLong(orgid));
    		filemode.setOrgName(orgname);
    		filemode.setGongyiId(Long.parseLong(gongyiid));
    		filemode.setGongyiName(gongyiname);
    		if(!"null".equals(modelCatalogue)){
        		filemode.setModelCatalogue(Integer.parseInt(modelCatalogue));
    		}
    		filemodeService.save(filemode);
    		
    		out.print("{\"ajaxResult\":\"success\"}");
    		out.flush();
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    }
     
    
    public void modifyFilemode()
    {
    	try{
    		//获取文件
    		PrintWriter out = PubMethod.GetPrintWriter(); 
    		HttpServletRequest request = this.getRequest();
    		//String _modename = request.getParameter("modename");
            String _path = request.getParameter("path");
            String type = request.getParameter("type");
            String rowindex =  request.getParameter("rowindex");
            String colindex =  request.getParameter("colindex");
            String modetype = request.getParameter("modetype");
            
//    		Filemode filemode = new Filemode();
//    		filemode.setId(Long.parseLong(_id));
    		String sid = request.getParameter("id");
    		StringBuffer buttonSb = new StringBuffer();
    		
    		if("excel".equals(type)){
    			String buttonSql = "update file_MODE t set t.file_path = '"+_path+"' ,t.rowindex='"+rowindex+"' ,t.colindex = '"+colindex+"',t.modetype="+modetype+" where t.id ="+sid;
        		autoService.executeSql(buttonSql);
    		}else if("word".equals(type)){
    			String buttonSql = "update report_mode t set t.report_path = '"+_path+"' where t.id ="+sid;
        		autoService.executeSql(buttonSql);
    		}else if("qita".equals(type)){
    			String buttonSql = "update PRINT_REPORT_MODE t set t.mode_path= '"+_path+"' where t.id ="+sid;
        		autoService.executeSql(buttonSql);
    		}
    		
    		
    		out.print("{\"ajaxResult\":\"success\"}");
    		out.flush();
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    }
    
    public void delFilemode() throws DaoException
    {
    	PrintWriter out = PubMethod.GetPrintWriter(); 
    	HttpServletRequest request = this.getRequest();
		String _ids = request.getParameter("ids");
		String[] idarray = _ids.split(",");
		for(int i=0;i<idarray.length;i++)
		{
			Filemode filemode = new Filemode();
    		filemode.setId(Long.parseLong(idarray[i]));
    		filemodeService.delete(filemode);
		}
		out.print("{\"ajaxResult\":\"success\"}");
    }
    
    public String initFilemode()
    {
    	HttpServletRequest request = this.getRequest();
		String sid = request.getParameter("id");
		StringBuffer buttonSb = new StringBuffer();
		if(extendname.equals("doc")){
			String buttonSql1 = "select t.report_name,t1.org_name,t.report_path,t.ysjl_id,t2.modetype,t.id from report_mode t left join sys_organization t1 on t1.org_id = t.org_name left join file_mode t2 on t2.id = t.ysjl_id where t.id="+sid;
			List buttonList1 = autoService.getDatabySql(buttonSql1);
			if(buttonList1 != null && buttonList1.size() != 0 ){
				for (int j = 0; j < buttonList1.size(); j++) {
					Object[] obj = (Object[])buttonList1.get(j);
					getRequest().setAttribute("reportObj", obj);
				}
			}
		}else{
			String buttonSql = "select t.id,t.file_name,t1.org_name,t2.standardname,t.file_path,t.rowindex,t.colindex,t.modetype from file_mode t left join sys_organization t1 on t1.org_id = t.org_name left join DIC_STANDARD t2 on t2.id=t.gongyi_name where t.id="+sid;
			List buttonList = autoService.getDatabySql(buttonSql);
			
			if(buttonList != null && buttonList.size() != 0 ){
				for (int j = 0; j < buttonList.size(); j++) {
					Object[] obj = (Object[])buttonList.get(j);
					getRequest().setAttribute("obj", obj);
				}
			}
			
			String strSql = "select BASEINFOID,DATAINFOID from FILE_MODE where id='"+sid+"' ";
			List lists = autoService.getDatabySql(strSql);
			Object[] objs = (Object[])lists.get(0);
			StringBuilder sbbase = new StringBuilder();
			if (objs[0]!=null){
				strSql = "select FIELD_NAME,CN_NAME from auto_forms_field t where forms_id="+objs[0]+" and field_name not in ('ID','FLOWTASKID','FILEMODEID')";
				List baseList = autoService.getDatabySql(strSql);
				for(int i=0;i<baseList.size();i++){
					Object[] objBases = (Object[])baseList.get(i);
					sbbase.append("<span  onclick=\"addBookmark1('fl_"+objBases[0]+"');\">"+objBases[1]+"</span><br>");
				}
			}
			getRequest().setAttribute("baseinfo", sbbase.toString());
			
			StringBuilder sbdata = new StringBuilder();
			if (objs[1]!=null){
				strSql = "select FIELD_NAME,CN_NAME from auto_forms_field t where forms_id="+objs[1]+" and field_name not in ('ID','FLOWTASKID','FILEMODEID')";
				List dataList = autoService.getDatabySql(strSql);
				for(int i=0;i<dataList.size();i++){
					Object[] objDatas = (Object[])dataList.get(i);
					sbdata.append("<span  onclick=\"addBookmark1('fdc_"+objDatas[0]+"');\">"+objDatas[1]+"</span><br>");
				}
			}
			getRequest().setAttribute("datainfo", sbdata.toString());
		}
		
    	String opentype = request.getParameter("opentype");
    	if("edit".equals(opentype)){
    		String modelCatalogue = request.getParameter("modelCatalogue");
    		getRequest().setAttribute("modelCatalogue", modelCatalogue);
    		if(extendname.equals("doc")){
    			return "editWordPage";
    		}else{
    			return "editExcelPage";
    		}
    	}else{
    		return "viewExcelPage";
    	}
    }
    
    public String initYsjlForm()
    {
		String sid = getRequest().getParameter("id");
		String strSql = "select t1.BASEINFOID,t1.DATAINFOID,t2.form_cn_name as f1,t3.form_cn_name as f2 from FILE_MODE t1 " +
				"left join auto_forms_new t2 on t1.baseinfoid=t2.id " +
				"left join auto_forms_new t3 on t1.datainfoid=t3.id where t1.ID='"+sid+"'";
		List lists = autoService.getDatabySql(strSql);
		getRequest().setAttribute("YSJLID", sid);
		if (lists.size()>0){
			Object[] objs = (Object[])lists.get(0);
			getRequest().setAttribute("BASEINFOID", objs[0]);
			getRequest().setAttribute("DATAINFOID", objs[1]);
			getRequest().setAttribute("BASEINFONAME", objs[2]);
			getRequest().setAttribute("DATAINFONAME", objs[3]);
		}
		return "initYsjlForm";
    }
    
    public void updateYsjlForm(){
    	String YSJLID = getRequest().getParameter("YSJLID");
    	String BASEINFOID = getRequest().getParameter("BASEINFOID");
    	String DATAINFOID = getRequest().getParameter("DATAINFOID");
    	String strSql = "update FILE_MODE set BASEINFOID='"+BASEINFOID+"',DATAINFOID='"+DATAINFOID+"' where id='"+YSJLID+"'";
    	autoService.executeSql(strSql);
    	PrintWriter out = PubMethod.GetPrintWriter(); 
    	out.print("{\"result\":\"success\"}");
    }
    
    public String initCentificatemode()
    {
    	HttpServletRequest request = this.getRequest();
		String sid = request.getParameter("id");
		StringBuffer buttonSb = new StringBuffer();
		String buttonSql = "select t.id,t.CENTIFICATE_NAME,t1.org_name,t2.standardname,t.CENTIFICATE_PATH from CENTIFICATE_MODE t left join sys_organization t1 on t1.org_id = t.org_name left join DIC_STANDARD t2 on t2.id=t.gongyi_name where t.id="+sid;
		List buttonList = autoService.getDatabySql(buttonSql);
		String foreignId = "";
		
		if(buttonList != null && buttonList.size() != 0 ){
			for (int j = 0; j < buttonList.size(); j++) {
				Object[] obj = (Object[])buttonList.get(j);
				if(null!=obj[0]){
					foreignId = obj[0].toString();
				}
				getRequest().setAttribute("obj", obj);
			}
		}
    	//Filemode filemode = filemodeService.getFilemodeById(Integer.parseInt(sid));
		//this.setModename(filemode.getFilename());
    	//this.setFilepath(filemode.getFilepath());
    	//if (filemode.getFilepath().indexOf("doc")>0)
    	//{
    	//	this.setExtendname("doc");
    	//}
    	//else
    	//{
    	//	this.setExtendname("xls");
    	//}
    	String opentype = request.getParameter("opentype");
    	Long seqValues = 1l;
    	if("edit".equals(opentype)){
    		String modelCatalogue = request.getParameter("modelCatalogue");
    		if(!"".equals(foreignId)){
    			String sql = "select max(t.biaoqian_seq)  from TDM_CENTIFICATEMODE_ITEM t  where t.CENTIFICATE_MODE_ID ="+foreignId;
    		    List list = autoService.getDatabySql(sql);
    		    if(null!=list&&list.size()>0){
    		    	if(null!=list.get(0)){
    		    		seqValues = Long.parseLong(list.get(0).toString())+1;
    		    	}
    		    }
    		}
    		getRequest().setAttribute("seqValues",seqValues);
    		getRequest().setAttribute("modelCatalogue", modelCatalogue);
    		//if(extendname.equals("doc")){
    		//	return "editWordPage";
    		//}else{
    			return "editWordPage";
    		//}
    	}else{
    		//if(extendname.equals("doc")){
    		//	return "viewWordPage";
    		//}else{
    			return "viewWordPage";
    		//}
    	}
    }
    /**
     * 初始化打印报告模板
     * @author zhn
     * @date Dec 2, 2013 7:56:39 PM
     * @return
     */
    public String initPrintReportmode()
    {
    	HttpServletRequest request = this.getRequest();
		String sid = request.getParameter("id");
		String flag = request.getParameter("flag");
		StringBuffer buttonSb = new StringBuffer();
		String buttonSql = "select t.id,t.mode_name,t1.org_name,t2.type_name, t3.form_cn_name,t.mode_path from PRINT_REPORT_MODE t left join sys_organization t1 on t1.org_id = t.choose_dept_id "+
                          " left join tdm_annex_type t2 on t2.id = t.choose_category_id left join AUTO_FORMS_NEW t3 on t3.id = t.choose_form_id where t.id="+sid;
		List buttonList = autoService.getDatabySql(buttonSql);
		
		if(buttonList != null && buttonList.size() != 0 ){
			for (int j = 0; j < buttonList.size(); j++) {
				Object[] obj = (Object[])buttonList.get(j);
				getRequest().setAttribute("obj", obj);
			}
		}
		if("0".equals(flag)){
			return "editQiTaWordPage";
		}else{
			return "editQiTaExcelPage";
		}
    	
    }
    public String rationalizeFilemode() throws Exception
    {
    	HttpServletRequest request = this.getRequest();
		String paraFilepath = request.getParameter("filepath");
		String timeFolder = paraFilepath.substring(0,6) + File.separator + paraFilepath;
    	this.setFilepath(paraFilepath);
    	String flag = request.getParameter("flag");
    	getRequest().setAttribute("flag", flag);
    	String relativePath = request.getParameter("relativePath");
    	getRequest().setAttribute("relativePath", relativePath);
    	String flowType = request.getParameter("flowType");
    	getRequest().setAttribute("flowType", flowType);
    	String taskId = request.getParameter("taskId");
    	
    	Object[] obj = null;
    	
    	getRequest().setAttribute("fields", obj);
    	
    	if (paraFilepath.indexOf("doc")>0)
    	{
    		getRequest().setAttribute("filetype", "doc");
    		return "editWordPageRationalize";
    	}
    	else
    	{
    		getRequest().setAttribute("filetype", "xls");
    		return "editExcelPageRationalize";
    	}
    }
    public String saveNewBiaoqian() throws IOException {
		setContentType();
		PrintWriter out = getResponse().getWriter();
		try {
			String formId = "";
			String columns = "";
			String values = "";
			String id = getRequest().getParameter("id");
			String num = getRequest().getParameter("num");
      		TdmCentificatemodeItem modeItem = filemodeService.queryModeItemById(Long.parseLong(id));
      		
            String formSql = "select t.id from auto_forms_new t where t.form_en_name = 'TDM_CENTIFICATEMODE_ITEM'";
            List formList =  autoService.getDatabySql(formSql);
            if(null!=formList&&formList.size()>0){
            	if(null!=formList.get(0)){
            		formId = formList.get(0).toString();
            	}
            }
            if(!"".equals(formId))
            {
            	//查询字段信息
				List<AutoFormsField> fieldList = autoFormService.getAutoFormsFieldByformid(formId);
				if(null!=fieldList&&fieldList.size()>0){
					for(AutoFormsField field : fieldList){
						String value = "";
						if(field.getFieldName().equals("ITEM_NAME")||field.getFieldName().equals("ID")||field.getFieldName().equals("BIAOQIAN_SEQ")){
							continue;
						}
						else{
							
							String sqlValus = "select "+field.getFieldName()+" from TDM_CENTIFICATEMODE_ITEM where ID = "+id;
							List listValue = autoService.getDatabySql(sqlValus);//查询所有的数据项
							if(listValue != null && listValue.size() != 0){
								if(null!=listValue.get(0))
									value = listValue.get(0).toString();
							}
						}
						values += ",'" + value+"'";
						columns +=  ","+ field.getFieldName() ;
					}
					String sql = "insert into TDM_CENTIFICATEMODE_ITEM (ID,BIAOQIAN_SEQ,"+columns.substring(1)+", ITEM_NAME)values(SEQ_TDM_CENTIFICATEMODE_ITEM.Nextval,"+num+","+values.substring(1)+",'"+modeItem.getItemName()+"_"+num+"')";
					
					autoService.executeSql(sql);
					
				}
				out.print("{\"ajaxResult\":\"success\"}");
			}else{
				out.print("{\"ajaxResult\":\"error\"}");
			}
			out.flush();
			out.close();
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			out.print("{\"ajaxResult\":\"error\"}");
			out.flush();
			out.close();
			return null;
		}

	}
    
    /**
	 * 下载所有的原始记录模版，合格证，打印单等等
	 * @throws Exception
	 */
	public void getFileDownloadYsjlHgz() throws Exception{
		String pathname = getRequest().getParameter("path");
		String type = getRequest().getParameter("type");
		String pathUrl = getRequest().getSession().getAttribute("SYS_FILEPATH").toString();
		String path = "";
		path = pathUrl+"/taskfile/"+type+"/"+pathname;
		//String url = PubMethod.GetFilepathfromproperties("zhiliangka");
		//String path = new String(getRequest().getParameter("filePath").getBytes("ISO-8859-1"));
		//path = url+"/"+StringUtil.encodingUrl(path);
		if(!"".equals(path)){
			File file=new File(path);//构造要下载的文件	
			if(file.exists()){
				InputStream ins=new FileInputStream(path);//构造一个读取文件的IO流对象
				BufferedInputStream bins=new BufferedInputStream(ins);//放到缓冲流里面
				OutputStream outs=getResponse().getOutputStream();//获取文件输出IO流
				BufferedOutputStream bouts=new BufferedOutputStream(outs);
				getResponse().setContentType("application/x-download");//设置response内容的类型
				getResponse().setHeader("Content-disposition","attachment;filename="+ URLEncoder.encode(path, "UTF-8"));//设置头部信息
				int bytesRead = 0;
				byte[] buffer = new byte[8192];
				//开始向网络传输文件流
				while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {
					bouts.write(buffer, 0, bytesRead);
				}
				bouts.flush();//这里一定要调用flush()方法
				ins.close();
				bins.close();
				outs.close();
				bouts.close();
			}else{
				System.out.println("下载的文件不存在");
			}
		}else{
			System.out.println("下载文件时参数错误");
		}

	}
	
	public void getFileDownload() throws Exception{
		String path = getRequest().getParameter("path");
		if(!"".equals(path)){
			File file=new File(path);//构造要下载的文件	
			if(file.exists()){
				InputStream ins=new FileInputStream(path);//构造一个读取文件的IO流对象
				BufferedInputStream bins=new BufferedInputStream(ins);//放到缓冲流里面
				OutputStream outs=getResponse().getOutputStream();//获取文件输出IO流
				BufferedOutputStream bouts=new BufferedOutputStream(outs);
				getResponse().setContentType("application/x-download");//设置response内容的类型
				getResponse().setHeader("Content-disposition","attachment;filename="+ URLEncoder.encode(path, "UTF-8"));//设置头部信息
				int bytesRead = 0;
				byte[] buffer = new byte[8192];
				//开始向网络传输文件流
				while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {
					bouts.write(buffer, 0, bytesRead);
				}
				bouts.flush();//这里一定要调用flush()方法
				ins.close();
				bins.close();
				outs.close();
				bouts.close();
			}else{
				System.out.println("下载的文件不存在");
			}
		}else{
			System.out.println("下载文件时参数错误");
		}

	}
	
	/**
	 * 模板列表
	 * @author zhn
	 * @date Dec 2, 2013 7:40:47 PM
	 */
	public void queryTempletList(){
		try {
			Map<String, String> filterMap = getPagerMap();
			String modelname = getRequest().getParameter("modelname");
			if (modelname != null && !"".equals(modelname)) {
				modelname = StringUtil.encodingUrl(modelname);
				modelname =StringUtil.escapeString(modelname);
			}
			filterMap.put("modelname", modelname);
			String[] viewArray = {"ID", "mode_name","button_name","choose_dept", "choose_form", "mode_path"};
			// 查询所有的数据
			PageResult result = filemodeService.queryTempletList(filterMap);
			String returnStr = getColumnJson(result, viewArray);
			PrintWriter out = PubMethod.GetPrintWriter(); 
			out.print(returnStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 修改、查看打印模版
	 * @author zhn
	 * @date Dec 2, 2013 6:20:41 PM
	 * @return
	 */
	public String toUpdateTemplet() {
		
		try {
			Long id = Long.parseLong(getRequest().getParameter("id"));
			String flag = getRequest().getParameter("flag");
			PrintReportMode printReportMode = filemodeService.toUpdateTemplet(id);
			 getRequest().setAttribute("printReportMode",printReportMode);
			if("edit".equals(flag)){
				return "edit";
			}else{
				return "view";
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
		
	}
	 /**
	  * 删除打印模版
	  * @throws Exception
	  */
	 public void deleteTemplet() throws Exception{
		  	PrintWriter out = getResponse().getWriter();
		  	try {
				String ids=getRequest().getParameter("ids");
				 if(ids !=null&&! ids.isEmpty()){
					 filemodeService.deleteTemplet(ids);
				 }
				 out.print("{\"result\":\"success\"}");
			} catch (Exception e) {
				e.printStackTrace();
				out.print("{\"result\":\"error\"}");
			}
	  }
	 /**
	 * 选择表单
	 * @author zhn
	 * @date Dec 2, 2013 5:53:59 PM
	 */
	public void queryFormList(){
		try {
			Map<String, String> filterMap = getPagerMap();
			String[] viewArray = {"ID", "FORM_CN_NAME", "FORM_EN_NAME"};
			// 查询所有的数据
			PageResult result = filemodeService.queryFormList(filterMap);
			String returnStr = getColumnJson(result, viewArray);
			PrintWriter out = PubMethod.GetPrintWriter(); 
			out.print(returnStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 保存方法
	 * @author zhn
	 * @date Dec 2, 2013 6:33:19 PM
	 * @throws ServiceException
	 */
	public void saveTemplet() throws ServiceException {
		
		try {
			PrintWriter out = getResponse().getWriter();
			//Long id = Long.parseLong(getRequest().getParameter("id"));
			
			PrintReportMode printReportMode = new PrintReportMode();
			printReportMode.setModeName(getRequest().getParameter("modeName"));
			printReportMode.setButtonName(getRequest().getParameter("buttonName"));
			printReportMode.setChooseDept(getRequest().getParameter("chooseDept"));
			printReportMode.setChooseDeptId(Long.parseLong(getRequest().getParameter("chooseDeptId")));
			//printReportMode.setChooseCategoryId(Long.parseLong(getRequest().getParameter("chooseCategoryId")));
			//printReportMode.setChooseCategory(getRequest().getParameter("chooseCategory"));
			printReportMode.setChooseFormId(Long.parseLong(getRequest().getParameter("chooseFormId")));
			printReportMode.setChooseForm(getRequest().getParameter("chooseForm"));
			filemodeService.saveTemplet(printReportMode);
			out.print("{\"result\":\"success\"}");
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * 修改方法
	 * @author zhn
	 * @date Dec 2, 2013 6:33:48 PM
	 * @throws ServiceException
	 */
	public void updateTemplet() throws ServiceException {
		
		try {
			PrintWriter out = getResponse().getWriter();
			Long id = Long.parseLong(getRequest().getParameter("id"));
			
			PrintReportMode printReportMode = filemodeService.toUpdateTemplet(id);
			//printReportMode.setId(id);
			printReportMode.setModeName(getRequest().getParameter("modeName"));
			printReportMode.setChooseDept(getRequest().getParameter("chooseDept"));
			printReportMode.setButtonName(getRequest().getParameter("buttonName"));
			printReportMode.setChooseDeptId(Long.parseLong(getRequest().getParameter("chooseDeptId").trim()));
			//printReportMode.setChooseCategoryId(Long.parseLong(getRequest().getParameter("chooseCategoryId").trim()));
			//printReportMode.setChooseCategory(getRequest().getParameter("chooseCategory"));
			printReportMode.setChooseFormId(Long.parseLong(getRequest().getParameter("chooseFormId").trim()));
			printReportMode.setChooseForm(getRequest().getParameter("chooseForm"));
			filemodeService.updateTemplet(printReportMode);
			out.print("{\"result\":\"success\"}");
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void getMergecelllist() throws Exception{
		try {
			Map<String, String> filterMap = getPagerMap();
		    //取出页面中的查询条件
			String filemodeid = getRequest().getParameter("filemodeid");
			filterMap.put("filemodeid", filemodeid);
			// 查询所有的数据
			PageResult result = filemodeService.queryMergecelllist(filterMap);
			String[] viewArray = { "ID", "tableindex", "startrow","startcolumn", "endrow","endcolumn", "result"};
			String returnStr = getColumnJson(result, viewArray);
			setContentType();
			PrintWriter out = getResponse().getWriter();
			out.print(returnStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void saveMergecell() throws IOException {
		PrintWriter out = getResponse().getWriter();
		try {
			String filemodeid = getRequest().getParameter("filemodeid");
			String tableindex = getRequest().getParameter("tableindex");
			String startrow = getRequest().getParameter("startrow");
			String startcolumn = getRequest().getParameter("startcolumn");
			String endrow = getRequest().getParameter("endrow");
			String endcolumn = getRequest().getParameter("endcolumn");
			String result = getRequest().getParameter("result");
			String mergecellid = getRequest().getParameter("mergecellid");
			if (mergecellid==null){
				String strSql = "insert into mergecell(id,filemodeid,tableindex,startrow,startcolumn,endrow,endcolumn," +
				"result) values (seq_mergecell_id.nextval,'"+filemodeid+"'," +
						"'"+tableindex+"','"+startrow+"','"+startcolumn+"','"+endrow+"','"+endcolumn+"','"+result+"')";
				autoFormService.executeSql(strSql);
			}
			else{
				String strSql = "update mergecell set tableindex='"+tableindex+"',startrow='"+startrow+"'," +
						"startcolumn='"+startcolumn+"',endrow='"+endrow+"',endcolumn='"+endcolumn+"',result='"+result+"'" +
						" where id='"+mergecellid+"'";
				autoFormService.executeSql(strSql);
			}
			out.print("{\"result\":\"success\"}");
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
			out.print("{\"result\":\"error\"}");
			out.flush();
			out.close();
		}
	}
	
	public String initEditMergecell(){
		try {
			String mergecellid = getRequest().getParameter("mergecellid");
			String strSql = "select t.id,t.tableindex,t.startrow,t.startcolumn,t.endrow,t.endcolumn,t.result" +
					" from mergecell t where t.id="+mergecellid;
			List lists = autoFormService.findAllBySql(strSql);
			if (lists.size()>0){
				 Object[] objs = (Object[])lists.get(0);
				 mergecellid = objs[0].toString();
				 this.getRequest().setAttribute("mergecellid", mergecellid);
				 this.getRequest().setAttribute("tableindex", objs[1]!=null?objs[1].toString():"");
				 this.getRequest().setAttribute("startrow", objs[2]!=null?objs[2].toString():"");
				 this.getRequest().setAttribute("startcolumn", objs[3]!=null?objs[3].toString():"");
				 this.getRequest().setAttribute("endrow", objs[4]!=null?objs[4].toString():"");
				 this.getRequest().setAttribute("endcolumn", objs[5]!=null?objs[5].toString():"");
				 this.getRequest().setAttribute("result", objs[6]!=null?objs[6].toString():"");
			}
			return "toeditmergecell";
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}
	
	public void deleteMergecell() throws IOException{
		PrintWriter out = getResponse().getWriter();
		try {
			String mergecellids = getRequest().getParameter("mergecellids");
			String strSql = "delete from mergecell  where id in ("+mergecellids+")";
			autoFormService.executeSql(strSql);
			out.print("{\"result\":\"success\"}");
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
			out.print("{\"result\":\"error\"}");
			out.flush();
			out.close();
		}
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getExtendname() {
		return extendname;
	}

	public void setExtendname(String extendname) {
		this.extendname = extendname;
	}

	public IAutoService getAutoService() {
		return autoService;
	}

	public void setAutoService(IAutoService autoService) {
		this.autoService = autoService;
	}

	public List getUploadfile() {
		return uploadfile;
	}

	public void setUploadfile(List uploadfile) {
		this.uploadfile = uploadfile;
	}

	public List getUploadfileContentType() {
		return uploadfileContentType;
	}

	public void setUploadfileContentType(List uploadfileContentType) {
		this.uploadfileContentType = uploadfileContentType;
	}

	public List getUploadfileFileName() {
		return uploadfileFileName;
	}

	public void setUploadfileFileName(List uploadfileFileName) {
		this.uploadfileFileName = uploadfileFileName;
	}

	public IAutoFormService getAutoFormService() {
		return autoFormService;
	}

	public void setAutoFormService(IAutoFormService autoFormService) {
		this.autoFormService = autoFormService;
	}
}
